<template>
  <div class="container mx-auto p-4">
    <app-header/>

    <!-- 过滤器面板 -->
    <div class="bg-white p-6 rounded-lg shadow-md mb-6 mt-4">
      <h2 class="text-xl font-bold text-gray-800 mb-4">日志查询</h2>

      <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">事件类型</label>
          <select v-model="filters.eventType" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
            <option value="">全部</option>
            <option value="SN_CheckIn">SN_CheckIn</option>
            <option value="SN_CheckOut">SN_CheckOut</option>
            <option value="Status">Status</option>
          </select>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">结果</label>
          <select v-model="filters.result" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
            <option value="">全部</option>
            <option value="PASS">PASS</option>
            <option value="FAIL">FAIL</option>
          </select>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">开始日期</label>
          <input type="date" v-model="filters.dateFrom" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">结束日期</label>
          <input type="date" v-model="filters.dateTo" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200 focus:ring-opacity-50">
        </div>
      </div>

      <div class="mt-6 flex justify-end space-x-3">
        <button @click="searchLogs" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors duration-200 flex items-center">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          查询
        </button>
        <button @click="exportLogs" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-opacity-50 transition-colors duration-200 flex items-center">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
          </svg>
          导出
        </button>
        <button @click="cleanupLogs" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-opacity-50 transition-colors duration-200 flex items-center">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
          </svg>
          清理旧日志
        </button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">事件类型</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">结果</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">消息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-if="loading">
              <td colspan="6" class="px-6 py-10 text-center">
                <div class="flex justify-center">
                  <svg class="animate-spin h-8 w-8 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                </div>
                <p class="mt-2 text-gray-500">加载中...</p>
              </td>
            </tr>
            <tr v-else-if="logs.length === 0">
              <td colspan="6" class="px-6 py-10 text-center">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p class="mt-2 text-gray-500">没有找到日志记录</p>
              </td>
            </tr>
            <tr v-for="log in paginatedLogs" :key="log.id" class="hover:bg-gray-50 transition-colors duration-150">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ log.id }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(log.timestamp) }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                <span class="px-2 py-1 text-xs font-semibold rounded-full" :class="getEventTypeClass(log.event_type)">
                  {{ log.event_type }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 py-1 text-xs font-semibold rounded-full" :class="log.result ==='PASS' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
                  {{ log.result }}
                </span>
              </td>
              <td class="px-6 py-4 text-sm text-gray-500 max-w-xs truncate">{{ log.message }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <router-link :to="`/mes-log/detail/${log.id}`" class="text-blue-600 hover:text-blue-900 flex items-center">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                  </svg>
                  详情
                </router-link>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页控件 -->
      <div class="bg-white px-6 py-4 border-t border-gray-200 flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <div class="text-sm text-gray-700">
            第 {{ totalPages === 0 ? 0 : currentPage }} 页 / 共 {{ totalPages }} 页 (共 {{ logs.length }} 条)
          </div>
          <div class="flex items-center space-x-2">
            <span class="text-sm text-gray-700">每页显示:</span>
            <select v-model="itemsPerPage" class="border border-gray-300 rounded-md text-sm py-1 px-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
              <option :value="10">10</option>
              <option :value="20">20</option>
              <option :value="50">50</option>
              <option :value="100">100</option>
            </select>
          </div>
        </div>
        <div class="flex space-x-2">
          <button
            @click="changePage(-1)"
            class="px-3 py-1 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
            :disabled="currentPage <= 1"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
            </svg>
            上一页
          </button>
          <button
            @click="changePage(1)"
            class="px-3 py-1 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed flex items-center"
            :disabled="currentPage >= totalPages"
          >
            下一页
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { getAllMesLogs, queryMesLogs, cleanupOldLogs, exportLogsAsJson } from '@/api/mesLogs'
import AppHeader from '@/components/AppHeader.vue';

export default {
  name: 'MesLog',
  components: {AppHeader},

  setup() {
    const logs = ref([])
    const loading = ref(false)

    // 分页状态
    const currentPage = ref(1)
    const itemsPerPage = ref(5) // 每页显示的条数

    const filters = reactive({
      eventType: '',
      result: '',
      dateFrom: '',
      dateTo: ''
    })

    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(logs.value.length / itemsPerPage.value)
    })

    // 计算当前页显示的日志
    const paginatedLogs = computed(() => {
      const startIndex = (currentPage.value - 1) * itemsPerPage.value
      const endIndex = startIndex + itemsPerPage.value
      return logs.value.slice(startIndex, endIndex)
    })

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }

    // 获取事件类型的样式
    const getEventTypeClass = (eventType) => {
      switch(eventType) {
        case 'SN_CheckIn':
          return 'bg-blue-100 text-blue-800';
        case 'SN_CheckOut':
          return 'bg-purple-100 text-purple-800';
        default:
          return 'bg-gray-100 text-gray-800';
      }
    }

    // 切换分页
    const changePage = (direction) => {
      const newPage = currentPage.value + direction
      if (newPage >= 1 && newPage <= totalPages.value) {
        currentPage.value = newPage
      }
    }

    // 加载所有日志
    const loadLogs = async () => {
      try {
        loading.value = true
        logs.value = await getAllMesLogs()
        // 重置到第一页
        currentPage.value = 1
      } catch (error) {
        console.error('加载日志失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 搜索日志
    const searchLogs = async () => {
      try {
        loading.value = true

        // 直接使用过滤器，不进行布尔值转换
        // 后端 API 已经修改为正确处理字符串类型的结果值
        logs.value = await queryMesLogs(filters)
        // 重置到第一页
        currentPage.value = 1
      } catch (error) {
        console.error('搜索日志失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 导出日志
    const exportLogs = async () => {
      try {
        // 直接使用过滤器，不进行布尔值转换
        const jsonData = await exportLogsAsJson(filters)
        if (!jsonData) {
          alert('导出失败: 没有数据')
          return
        }

        // 创建下载链接
        const blob = new Blob([jsonData], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `mes-logs-${new Date().toISOString().slice(0, 10)}.json`
        document.body.appendChild(a)
        a.click()

        // 清理
        setTimeout(() => {
          document.body.removeChild(a)
          URL.revokeObjectURL(url)
        }, 0)
      } catch (error) {
        console.error('导出日志失败:', error)
      }
    }

    // 清理旧日志
    const cleanupLogs = async () => {
      try {
        // 默认保留天数
        let days = 7;

        // 如果有 Electron API，使用对话框
        if (!confirm(`确定要清理 ${days} 天前的日志吗？`)) return;

        const count = await cleanupOldLogs(days);

        alert(`成功清理了 ${count} 条旧日志`);

        // 重新加载日志
        await loadLogs();
      } catch (error) {
        console.error('清理日志失败:', error);

        alert(`清理日志失败: ${error.message || '未知错误'}`);
      }
    }

    // 监听每页显示数量变化
    watch(itemsPerPage, () => {
      // 当每页显示数量变化时，重置到第一页
      currentPage.value = 1
    })

    // 组件挂载时加载日志
    onMounted(() => {
      loadLogs()
    })

    return {
      logs,
      paginatedLogs,
      loading,
      filters,
      currentPage,
      totalPages,
      itemsPerPage,
      changePage,
      searchLogs,
      exportLogs,
      cleanupLogs,
      formatDate,
      getEventTypeClass
    }
  }
}
</script>